# -*- coding: utf-8 -*-
import tornado
import asyncio
import app.tools.SafeMonitorTools.api as api
from app.views import SmBaseHandler
import json
import app.tools.SafeMonitorTools.m_position_layer_type as smType
mine_id = smType.default_MineId
# 根据条件 查询单个 m_position 记录
async def get_positions_singel(self,mine_id,service_type,node_id,layer):
    rows = await api.query_position(mine_id,service_type,node_id,layer)
    rowlen = len(rows)
    if rowlen > 0:
        # 提取row
        row = rows[0]
        respon = {}
        respon['mine_id'] = row[0]
        respon['node_id'] = row[1]
        respon['service_type'] = row[2]
        respon['x'] = row[3]
        respon['y'] = row[4]
        respon['layer'] = row[5]
        respon['rowguid'] = row[6]
        self.finish({'data':respon})
    else:
        self.finish({'data':{}})

# 根据条件 查询全部 m_position 记录
async def get_positions_all(self,mine_id):
    rows = await api.query_all_position(mine_id)
    rowlen = len(rows)
    if rowlen > 0:
        # 提取row
        rowList = list()
        for row in rows:
            respon = {}
            respon['mine_id'] = row[0]
            respon['node_id'] = row[1]
            respon['service_type'] = row[2]
            respon['x'] = row[3]
            respon['y'] = row[4]
            respon['layer'] = row[5]
            respon['rowguid'] = row[6]
            rowList.append(respon)
        self.finish({'data':rowList})
    else:
        self.finish({'data':[]})


class SmPositionHandler(SmBaseHandler):
    @tornado.gen.coroutine
    def get(self):
        service_type = self.get_query_argument('service_type')
        node_id = self.get_query_argument('node_id')
        layer = self.get_query_argument('layer')
        # 查询 m_position 内部全部信息
        if service_type == 'null' or node_id == 'null':
            yield get_positions_all(self,mine_id)
        else:
            # 查询 m_position 单个信息
            yield get_positions_singel(self,mine_id,service_type,node_id,layer)

    @tornado.gen.coroutine
    def post(self):
        info = json.loads(self.request.body)
        parList = []
        for el in info:
            turple = (el['mine_id'],el['node_id'],el['service_type'],el['x'],el['y'],el['layer'])
            parList.append(turple)
        flag = yield api.add_position(parList)
        if flag:
            self.finish({'code':'success'})
        else:
            self.finish({'code':'error'})

    @tornado.gen.coroutine
    def put(self):
        info = json.loads(self.request.body)

        flag = yield api.update_position(info)
        if flag:
            self.finish({'code':'update success'})
        else:
            self.finish({'code':'update error'})

    @tornado.gen.coroutine
    def delete(self):
        info = json.loads(self.request.body)
        flag = yield api.delete_position(info)
        if flag:
            self.finish({'code':'delete success','data':'success'})
        else:
            self.finish({'code':'delete error','data':'error'})
